class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def pathSum(self, root, targetSum):
        self.count = 0
        prefix_sum = {0: 1}
        
        def dfs(node, current_sum):
            if not node:
                return
            
            current_sum += node.val
            self.count += prefix_sum.get(current_sum - targetSum, 0)
            prefix_sum[current_sum] = prefix_sum.get(current_sum, 0) + 1
            
            dfs(node.left, current_sum)
            dfs(node.right, current_sum)
            
            # 回溯，移除当前路径的影响
            prefix_sum[current_sum] -= 1
        
        dfs(root, 0)
        return self.count    